package com.mjk.common.tools.monitor.impl;

import com.google.gson.Gson;
import com.mjk.common.core.health.info.HealthConstns;
import com.mjk.common.tools.gson.GsonUtils;
import com.mjk.common.tools.monitor.IMonitor;
import com.mjk.common.tools.monitor.impl.entity.SbaApplicationResponse;
import com.mjk.common.util.ComputerUtils;
import com.mjk.common.util.HttpUtils;
import com.mjk.common.util.MapUtils;
import com.mjk.common.util.ObjectUtils;
import de.codecentric.boot.admin.client.registration.Application;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 
 * @author Administrator
 *
 */
public class DefaultMonitor implements IMonitor {
	@Value("${spring.boot.admin.client.url:}")
	private String SBA_URL;
	@Override
    public List<ComputerUtils.ComputerInfo> getServices(String name) {
		List<ComputerUtils.ComputerInfo> infos = new ArrayList<>();
		if (ObjectUtils.isNotEmpty(SBA_URL)) {
			String result = HttpUtils.httpGet(SBA_URL + "/applications");
			if (ObjectUtils.isEmpty(result)) {//如果返回数据为空，说明请求服务有问题
				return infos;
			}
			List<SbaApplicationResponse> applications = GsonUtils.json2List(result, SbaApplicationResponse.class);
			if (CollectionUtils.isEmpty(applications)) {
				return infos;
			}
			//解析applications
			applications.stream().forEach(item -> {
				item.getInstances().stream().forEach(item1 -> {
					ComputerUtils.ComputerInfo info = new ComputerUtils.ComputerInfo();
					info.setIp(MapUtils.getString(item1.getInfo(), HealthConstns.HEALTH_APPINFO_ADDR));
					info.setPort(MapUtils.getString(item1.getInfo(), HealthConstns.HEALTH_APPINFO_PORT));
					info.setServiceName(MapUtils.getString(item1.getInfo(), HealthConstns.HEALTH_APPINFO_NAME));
					info.setShowName(info.getIp() + ":" + info.getPort());
					info.setMateInfo(MapUtils.get(item1.getInfo(), HealthConstns.HEALTH_APPINFO_MATEDATE, HashMap.class));
					infos.add(info);
				});
			});
			return infos;
		} else {
			return infos;
		}
	}

}
